package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.service.*;
import com.alibaba.dubbo.config.annotation.Reference;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(path = "/report")
@CrossOrigin
public class MemberCountController {
    @Reference
    private OrderService orderService;

    @Reference
    private PaylogService paylogService;

    @Reference
    private MemberService memberService;

    @Reference
    private OrderSettingService orderSettingService;


    @Reference
    private ResponseService responseService;

    /**
     * 查询最近12个月, 会员数量变化情况 , 以折线图展示出来
     *
     * @return
     */
    @GetMapping(path = "/member/count")
    public Result memberList() {
        try {

            //当前时间往后 12个月的时间
            List<String> months = this.getDateMonths();

            //返回容器
            Map<String, Object> map = new HashMap<>();
            //数据库查询到的 会员数据集合
            List<Integer> memberByMonths = memberService.findMemberByMonths(months);


            map.put("months", months);
            map.put("memberCount", memberByMonths);


            return new Result(true, MessageConstant.UPLOAD_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }


    }


    /**
     * 统计整个系统所有套餐的预约占比情况 , 以饼图展示出来
     *
     * @return
     */
    @GetMapping(path = "/setmeals")
    public Result orderByMap() {


        try {

            Map<String, Object> data = new HashMap<>();

            List<Map<String, Object>> setmealCount = orderService.countOrder();

            data.put("setmealCount", setmealCount);

            List<String> setmealNames = new ArrayList<>();

            for (Map<String, Object> map : setmealCount) {

                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            data.put("setmealName", setmealNames);

            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }

    }

    /**
     * 统计出最近12个月 , 每个月的收入情况, 以柱形图展示
     *
     * @return
     */
    @GetMapping("/paylog")
    public Result paylogMap() {

        try {

            List<String> months = this.getDateMonths();

            Map<String, Object> data = new HashMap<>();

            List<Integer> memberByMonths = this.paylogService.findMemberByMonths(months);

            data.put("months", months);
            data.put("memberCount", memberByMonths);

            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }


    }


    /**
     * 查询最近12个月的预约数量以及支付数量 , 以双折线图展示
     *
     * @return
     */
    @GetMapping("/orderSetting")
    public Result orderController() {

        try {

            List<String> months = this.getDateMonths();

            Map<String, Object> data = new HashMap<>();

            //预约数量
            List<Integer> settingCou = this.orderSettingService.findSettingByMonths(months);

            //根据时间查询 支付数量
            List<Integer> byPayStatus = this.paylogService.findByPayStatus(months);

            data.put("months", months);
            data.put("orderCou", settingCou);
            data.put("payCou", byPayStatus);
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();

            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }


    }

    /**
     * 获取时间轴的数据
     *
     * @return
     */
    private List<String> getDateMonths() {

        Calendar calendar = Calendar.getInstance(); //获取日历对象， 当前时间
        calendar.add(Calendar.MONTH, -12);    //当前时间往后 12个月的时间

        List<String> months = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date time = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy-MM").format(time));

        }

        return months;

    }

    /**
     * 热门套餐
     *
     * @return
     */
    @GetMapping("/business")
    public Result operationController() {

        try {
            Map<String, Object> data = this.responseService.getReportData();

            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();

            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }


    }

    @GetMapping("export/business")
    public Result ResponseExport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = this.responseService.getReportData();
            //取出返回结果数据 准备把报表数据写入ex 文件中；
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            // 动态获取文件的绝对路径
//                 String filePath = request.getSession().getServletContext().getRealPath("template")+ File.separator+"report_template.xlsx";


            //获取文件的绝对路径
            String basePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/template/";
            //Eexcel模板地址
            String filePath2 = basePath + "report_template.xlsx";


            //基于提供的Exce 模板文件在内存中创建一个Exce表格对象

            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath2)));
            //读取工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            //获取第3行
            XSSFRow row = sheet.getRow(2);
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(reportDate);   //报表时间

            row = sheet.getRow(4);
            cell = row.getCell(5);
            cell.setCellValue(todayNewMember); //新增会员数

            row = sheet.getRow(4);
            cell = row.getCell(7);
            cell.setCellValue(totalMember);  //总会员

            row = sheet.getRow(5);
            cell = row.getCell(5);
            cell.setCellValue(thisWeekNewMember);  //本周新增会员

            row = sheet.getRow(5);
            cell = row.getCell(7);
            cell.setCellValue(thisMonthNewMember);  //本月新增会员

            row = sheet.getRow(7);
            cell = row.getCell(5);
            cell.setCellValue(todayOrderNumber);  //今日预约

            row = sheet.getRow(7);
            cell = row.getCell(7);
            cell.setCellValue(todayVisitsNumber); //今日到诊

            row = sheet.getRow(8);
            cell = row.getCell(5);
            cell.setCellValue(thisWeekOrderNumber);//本周预约

            row = sheet.getRow(8);
            cell = row.getCell(7);
            cell.setCellValue(thisWeekVisitsNumber); //本周到诊数

            row = sheet.getRow(9);
            cell = row.getCell(5);
            cell.setCellValue(thisMonthOrderNumber); //本月预约数

            row = sheet.getRow(9);
            cell = row.getCell(7);
            cell.setCellValue(thisMonthVisitsNumber); //本月到诊数

            int rowNum = 12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");

                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);  //名称
                row.getCell(5).setCellValue(setmeal_count);  //数量
                row.getCell(6).setCellValue(proportion.doubleValue());  //占比


            }
            //使用输出流进行表格下载，基于浏览器作为客户端下载
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");  //代表的是Excel文件
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            excel.write(outputStream);

            outputStream.flush();
            outputStream.close();
            excel.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();

            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }


}


